package org.dtrd.modules.service.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.Constant.PackageServiceStatus;
import org.dtrd.modules.service.entity.po.DtrdRlPackagePatient;
import org.dtrd.modules.service.service.IDtrdRlPackagePatientService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author qr
 * @date 2022/2/11 15:03
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
@Slf4j
public class CheckServiceStatusJob implements Job {

    @Autowired
    private IDtrdRlPackagePatientService packagePatientRlService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LambdaQueryWrapper<DtrdRlPackagePatient> wrapper1 = Wrappers.lambdaQuery(DtrdRlPackagePatient.class)
                .in(DtrdRlPackagePatient::getStatus,
                        Constant.PackageServiceStatus.WAIT_TO_SERVICE.getType(),
                        Constant.PackageServiceStatus.SERVICING.getType());
        List<DtrdRlPackagePatient> list = packagePatientRlService.list(wrapper1);
        for (DtrdRlPackagePatient po : list) {
            Integer patientId = po.getPatientId();
            Integer packageId = po.getPackageId();
            Integer status = po.getStatus();
            // 待服务 -> 服务中
            if (status.equals(Constant.PackageServiceStatus.WAIT_TO_SERVICE.getType())
                    && !DateUtils.isFuture(po.getStartTime())) {
                po.setStatus(Constant.PackageServiceStatus.SERVICING.getType());
                log.info("----------患者: {}, 服务包: {} 开始服务----------", patientId, packageId);
            }
            // 服务中 -> 已结束
            if (status.equals(Constant.PackageServiceStatus.SERVICING.getType())
                    && !DateUtils.isFuture(po.getEndTime())) {
                po.setStatus(PackageServiceStatus.EXPIRE.getType());
                log.info("----------患者: {}, 服务包: {} 服务包到期----------", patientId, packageId);
            }
        }
        packagePatientRlService.updateBatchById(list);
    }
}
